package org.zhangkun.jmsg.ui.swing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.zhangkun.jmsg.bean.DataPack;
import org.zhangkun.jmsg.bean.Msg;
import org.zhangkun.jmsg.bean.User;
import org.zhangkun.jmsg.core.UserManager;
import org.zhangkun.jmsg.core.listener.UserListener;
import org.zhangkun.jmsg.core.network.NetConnection;
import org.zhangkun.jmsg.core.network.NetConnection.LoadingListener;
import org.zhangkun.jmsg.ui.swing.view.UserTreePanel;
import org.zhangkun.jmsg.util.FileUtil;
import org.zhangkun.jmsg.util.GlobalVar;
import org.zhangkun.jmsg.util.Res;
import org.zhangkun.jmsg.util.StrUtil;
import org.zhangkun.jmsg.webserver.server.WEBServer;


public class MainWindow extends JFrame implements LoadingListener {

    public final static MainWindow instance = new MainWindow();
    /**
     *
     */
    private static final long serialVersionUID = -6901436376778386989L;
    private ArrayList<SendMsgDialog> allSendDialog = new ArrayList<SendMsgDialog>();
    private GroupMsg groupMsg;
    private JLabel onlineUserNum;
    private TrayDialog tray;
    private UserTreePanel userTreePanel;

    public MainWindow() {
        initGUI();
        UserManager.addUserListener(new UserListener() {

            public void removeUser(User u) {
                // TODO Auto-generated method stub
                updateUserNumber();
            }

            public void modifyUser(User u) {
                // TODO Auto-generated method stub
                updateUserNumber();
            }

            public void delAllUser() {
                // TODO Auto-generated method stub
                updateUserNumber();
            }

            public void addUser(User u) {
                // TODO Auto-generated method stub
                updateUserNumber();
            }
        });
        setResizable(false);
    }

    public void updateUserNumber() {
        onlineUserNum.setText("在线人数:"
                + UserManager.instance.getAllUser().size());
    }

    /**
     * 接收消息
     */
    public void addMsg(User user, Msg msg) {
        if (groupMsg != null) {
            if (groupMsg.getUserTreePanel().getSelUser().contains(user)) {
                groupMsg.addMsg(user, msg);
                return;
            }
        }
        SendMsgDialog sd = getSendDialog(user);
        if (sd == null) {
            if (msg.getType() == Msg.MSG_START_INPUT
                    || msg.getType() == Msg.MSG_END_INPUT) {
                return;
            }
            if (msg.getType() == Msg.MSG_SHAKE) {
                int ti = tray.getSendMsgDialogIndex(user);
                if (ti == -1) {
                    SendMsgDialog nsd = new SendMsgDialog(user);
                    allSendDialog.add(nsd);
                    nsd.addMsg(msg);
                } else {
                    tray.openSendDialog(ti).addMsg(msg);
                }
            } else {
                if (!GlobalVar.MSG_DIRECT_POP_UP)
                    tray.addMsg(user, msg);
                else {
                    int ti = tray.getSendMsgDialogIndex(user);
                    if (ti == -1) {
                        SendMsgDialog nsd = new SendMsgDialog(user);
                        allSendDialog.add(nsd);
                        nsd.addMsg(msg);
                    } else {
                        tray.openSendDialog(ti).addMsg(msg);
                    }
                }
            }
        } else
            sd.addMsg(msg);
    }

    public void closeSendDialog(SendMsgDialog sendDialog) {
        // TODO Auto-generated method stub
        allSendDialog.remove(sendDialog);
    }

    public ArrayList<SendMsgDialog> getAllSendDialog() {
        return allSendDialog;
    }

    public String getColor(Color color) {
        return color.getRed() + "," + color.getGreen() + "," + color.getBlue();
    }

    public GroupMsg getGroupMsg() {
        return groupMsg;
    }

    public SendMsgDialog getSendDialog(User user) {
        for (SendMsgDialog sd : allSendDialog)
            if (sd.getUser().equals(user))
                return sd;
        return null;
    }

    public TrayDialog getTray() {
        return tray;
    }

    public void init() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                setVisible(false);
            }
        });

        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        URL url = getClass().getResource("/res/Snow.theme");

        tray = new TrayDialog();

        try {
            NetConnection.instance.init(this);
            if (!WEBServer.instance.init()) {
                SystemTray.getSystemTray().remove(tray.getIcon());
                getTray().dispose();
                dispose();
                JOptionPane.showMessageDialog(this, "WEB服务器无法启动！", "初始化失败",
                        JOptionPane.ERROR_MESSAGE);
                NetConnection.instance.close();
                System.exit(0);
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            SystemTray.getSystemTray().remove(tray.getIcon());
            getTray().dispose();
            dispose();
            JOptionPane.showMessageDialog(this,
                    "监听端口(TCP:2425)错误，请确认没有其他飞鸽类程序在运行！", "初始化失败",
                    JOptionPane.ERROR_MESSAGE);
            e1.printStackTrace();
            NetConnection.instance.close();
            System.exit(0);
        }
        this.setVisible(true);

    }

    public void initGUI() {
        setTitle("JMsg");
        setIconImage(Res.JMSG_LOGO_IMG);
        // getContentPane().setBackgroundDecorator();

        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.SOUTH);
        {
            refreshLab = new JLabel("");
            refreshLab.setIcon(new ImageIcon(MainWindow.class
                    .getResource("/res/loading.gif")));
            panel.add(refreshLab);
        }

        onlineUserNum = new JLabel("在线人数");
        panel.add(onlineUserNum);

        userTreePanel = new UserTreePanel(null, UserTreePanel.SHOW_MODEL_LIST);
        getContentPane().add(userTreePanel, BorderLayout.CENTER);

        this.setSize(212, 500);
        int w = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        int h = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        this.setLocation((w - 400), (h - 500) / 2);
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        {
            JMenu menu = new JMenu("消息");
            menuBar.add(menu);
            {
                JMenuItem menuItem = new JMenuItem("发送消息");
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/mail-message-new.png")));
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        Object obj = userTreePanel.getSelect();
                        if (obj instanceof User) {
                            openSendDialog((User) obj);
                        }
                    }
                });
                menu.add(menuItem);
            }
            {
                JMenuItem menuItem = new JMenuItem("发送文件");
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/document-new.png")));
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        Object obj = userTreePanel.getSelect();
                        if (obj instanceof User) {
                            new SendFileDialog((User) obj);
                        }
                        // int index = userList.getSelectedIndex();
                        // if (index != -1)
                        // new SendFileDialog((User) userListModel
                        // .getElementAt(index));
                    }
                });
                menu.add(menuItem);
            }
            {
                JMenuItem pocketTransmissionItem = new JMenuItem("群发消息");
                pocketTransmissionItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
                        openGroupMsg();
                    }
                });
                pocketTransmissionItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/im-message-new.png")));
                menu.add(pocketTransmissionItem);
            }
            {
                JSeparator separator = new JSeparator();
                menu.add(separator);
            }
            {
                JMenuItem menuItem = new JMenuItem("探测");
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        String ip = JOptionPane.showInputDialog("请输入探测IP:");
                        if (ip != null) {
                            if (StrUtil.verifyIPAddres(ip)) {
                                DataPack dp = new DataPack();
                                dp.setSendToHostAddres(ip);
                                dp.setDataType(DataPack.IPMSG_BR_ENTRY);
                                NetConnection.instance.sendBroadcast(dp);
                                System.out.println("探测：" + ip);
                            } else {
                                JOptionPane.showMessageDialog(MainWindow.this,
                                        "输入的IP地址不合法！");
                            }
                        }
                    }
                });
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/menu-detect.png")));
                menu.add(menuItem);
            }
            {
                JMenuItem menuItem = new JMenuItem("查找");
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        new FindUserDialog();
                    }
                });
                {
                    JMenuItem menuItem_1 = new JMenuItem("扫描");
                    menuItem_1.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent arg0) {
                            HostListDialog.open();
                        }
                    });
                    menu.add(menuItem_1);
                }
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/edit-find.png")));
                menu.add(menuItem);
            }
            {
                JSeparator separator = new JSeparator();
                menu.add(separator);
            }
            {
                JSeparator separator = new JSeparator();
                menu.add(separator);
            }
            {
                JMenuItem menuItem = new JMenuItem("退出");
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/application-exit.png")));
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        exit();
                    }

                });
                menu.add(menuItem);
            }
        }
        {
            JMenu menu = new JMenu("查看");
            menuBar.add(menu);
            {
                JMenuItem menuItem = new JMenuItem("设置");
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/gtk-preferences.png")));
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        SetDialog.create(MainWindow.this);
                    }
                });
                menu.add(menuItem);
            }
            {
                JMenuItem menuItem = new JMenuItem("文件传输管理器");
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/system-file-manager.png")));
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        FileTransportViewDialog.create().setVisible(true);
                    }
                });
                menu.add(menuItem);
            }
            {
                JMenuItem menuItem = new JMenuItem("刷新");
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/view-refresh.png")));
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        refresh();
                    }
                });
                {
                    JMenuItem menuItem_1 = new JMenuItem("个人资料");
                    menuItem_1.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            JOptionPane.showMessageDialog(
                                    MainWindow.this,
                                    "个人资料：" + UserManager.me.getName()
                                            + "\n主机："
                                            + UserManager.me.getHostName()
                                            + "\nIP：" + UserManager.me.getIp()
                                            + "\n分组："
                                            + UserManager.me.getGroup());
                        }
                    });
                    menuItem_1.setIcon(new ImageIcon(MainWindow.class
                            .getResource("/res/web/sendMeBtn.png")));
                    menu.add(menuItem_1);
                }
                menu.add(menuItem);
            }
        }
        {
            JMenu menu = new JMenu("界面");
            menuBar.add(menu);
            {
                JMenuItem menuItem = new JMenuItem("Java风格");
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        updateLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                    }
                });
                JMenuItem menuItem_1 = new JMenuItem("当前系统风格");
                menuItem_1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        updateLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    }
                });
                menu.add(menuItem);
                menu.add(menuItem_1);
            }
        }
        {
            JMenu menu = new JMenu("帮助");
            menuBar.add(menu);
            {
                final JMenuItem menuItem = new JMenuItem("关于");
                menuItem.setIcon(new ImageIcon(MainWindow.class
                        .getResource("/res/help-about.png")));
                menuItem.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        about();
                    }
                });
                menu.add(menuItem);
            }
        }

    }

    public void exit() {
        // TODO Auto-generated method stub
        for (int i = 0; i < allSendDialog.size(); i++)
            allSendDialog.get(i).dispose();
        dispose();
        tray.dispose();
        SystemTray.getSystemTray().remove(tray.getIcon());
        new Thread(new Runnable() {
            public void run() {
                NetConnection.instance.close();
                FileUtil.deleteAllTempFile();
                System.exit(0);
            }
        }, "exit Thread").start();
    }

    public void about() {
        JOptionPane.showMessageDialog(MainWindow.this,
                "软件作者：张坤（雨坤毅）\n软件版本：2.0\n邮箱：yukunyi@yeah.net\nQQ：690783243\n\n"
                        + "本软件是采用Java编写的一个局域网通讯程序，兼容飞鸽传书协议。", "关于本软件",
                JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     *
     */

    public void openSendDialog(User user) {
        // TODO Auto-generated method stub
        if (getSendDialog(user) == null) {
            int index = tray.getSendMsgDialogIndex(user);
            if (index != -1) {
                tray.openSendDialog(index);
            } else
                allSendDialog.add(new SendMsgDialog(user));
        }
    }

    private boolean refreshing = true;
    private JLabel refreshLab;

    public void refresh() {

        if (refreshing)
            return;
        refreshing = true;
        refreshLab.setVisible(true);

        ArrayList<User> allUser = new ArrayList<User>(
                UserManager.instance.getAllUser());
        UserManager.instance.delAllUser();
        new Thread(new Runnable() {
            private ArrayList<User> allUser;

            private Runnable setAllUser(ArrayList<User> allUser) {
                this.allUser = allUser;
                return this;
            }

            public void run() {
                // NetConnection.instance.refresh(allUser);
                NetConnection.instance.landing(allUser);
                allUser = null;
                refreshing = false;
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {

                        public void run() {
                            // TODO Auto-generated method stub
                            refreshLab.setVisible(false);
                        }
                    });
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.setAllUser(allUser), "Refresh Thread").start();
        allUser = null;
    }

    /**
     * 重列表中移除一个用户
     *
     * @param u
     */
    public void removeUser(User u) {
        // TODO Auto-generated method stub
    }

    public void setGroupMsg(GroupMsg groupMsg) {
        this.groupMsg = groupMsg;
    }

    public void updateLookAndFeel() {
        SwingUtilities.updateComponentTreeUI(this);
        if (tray != null)
            SwingUtilities.updateComponentTreeUI(tray);
        if (allSendDialog != null)
            for (int i = 0; i < allSendDialog.size(); i++)
                SwingUtilities.updateComponentTreeUI(allSendDialog.get(i));

        if (FileTransportViewDialog.instance != null)
            SwingUtilities
                    .updateComponentTreeUI(FileTransportViewDialog.instance);
        if (SetDialog.instance != null)
            SwingUtilities.updateComponentTreeUI(SetDialog.instance);
        if (userTreePanel != null)
            userTreePanel.updateTree();
    }

    public void updateLookAndFeel(LookAndFeel lnfName) {
        try {
            UIManager.setLookAndFeel(lnfName);
            updateLookAndFeel();
        } catch (UnsupportedLookAndFeelException ex1) {
            System.err.println("Unsupported LookAndFeel: " + lnfName);
        }
    }

    public void updateLookAndFeel(String lnfName) {
        try {
            UIManager.setLookAndFeel(lnfName);
            updateLookAndFeel();
        } catch (UnsupportedLookAndFeelException ex1) {
            System.err.println("Unsupported LookAndFeel: " + lnfName);
        } catch (ClassNotFoundException ex2) {
            System.err.println("LookAndFeel class not found: " + lnfName);
        } catch (InstantiationException ex3) {
            System.err.println("Could not load LookAndFeel: " + lnfName);
        } catch (IllegalAccessException ex4) {
            System.err.println("Cannot use LookAndFeel: " + lnfName);
        }
    }

    public void openGroupMsg() {
        // TODO Auto-generated method stub
        if (groupMsg == null) {
            groupMsg = new GroupMsg();
        } else {
            groupMsg.setVisible(true);
            groupMsg.requestFocusInWindow();
        }
    }

    public JLabel getRefreshLab() {
        return refreshLab;
    }

    public void loading() {
        // TODO Auto-generated method stub
    }

    public void loadfinish() {
        // TODO Auto-generated method stub
        refreshing = false;
        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                public void run() {
                    // TODO Auto-generated method stub
                    refreshLab.setVisible(false);
                }
            });
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public UserTreePanel getUserTreePanel() {
        return userTreePanel;
    }

    public void setUserTreePanel(UserTreePanel userTreePanel) {
        this.userTreePanel = userTreePanel;
    }

}
